package com.ramos.kuaixiao.db;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteStatement;
import android.util.Log;

import com.ramos.kuaixiao.entity.FirstPrice;
import com.ramos.kuaixiao.utils.SharedPreference;
import com.ramos.kuaixiao.utils.StringUtil;
import com.ramos.kuaixiao.utils.Utils;

import java.util.ArrayList;
import java.util.List;

public class PriceDB {
    private static String TAG = "PriceDB";
    private static String TABLE_NAME = "Price";
    public static final String CREATE_TABLE_SQL;
    public static final String DROP_USERINFO;

    static {
        CREATE_TABLE_SQL = "CREATE TABLE " + TABLE_NAME + " (" + "idx  CHAR(30) PRIMARY KEY  NOT NULL,"
                + "productInfoId" + " CHAR(30)," + "productInfoName" + " CHAR(30)," + "dealerId" + " CHAR(30)," + "priceTypeId" + " CHAR(30),"
                + "priceTypeName" + " CHAR(30)," + "taxSalePrice" + " CHAR(30),"  + "noTaxSalePrice" + " CHAR(30)," + "taxSaleSinglePrice" + " CHAR(30),"
                + "last_discount" + "  CHAR(30),"+ "modifyTime" + " Long);";
        DROP_USERINFO = "DROP TABLE IF EXISTS " + TABLE_NAME;
    }

    public int addAllPrice(List<FirstPrice> customer) {
        //deleteAll();
        SQLiteDatabase db = DBHelper.open();
        db.execSQL("DELETE FROM Price");
        String sql = "insert into Price(idx,productInfoId,productInfoName,dealerId,priceTypeId,priceTypeName,taxSalePrice,noTaxSalePrice,taxSaleSinglePrice,last_discount,modifyTime) values(?,?,?,?,?,?,?,?,?,?,?)";
        db.beginTransaction();
        Long a = System.currentTimeMillis();
        SQLiteStatement stmt = db.compileStatement(sql);
        for (int i = 0; i < customer.size(); i++) {
            stmt.bindString(1, customer.get(i).getProductInfoId() + "");
            stmt.bindString(2, customer.get(i).getProductInfoName() + "");
            stmt.bindString(3, customer.get(i).getDealerId() + "");
            stmt.bindString(4, customer.get(i).getPriceTypeId() + "");
            stmt.bindString(5, customer.get(i).getPriceTypeName() + "");
            stmt.bindString(6, customer.get(i).getTaxSalePrice() + "");
            stmt.bindString(7, customer.get(i).getNotaxSalePrice() + "");
            stmt.bindString(8, customer.get(i).getTaxSaleSinglePrice() + "");
            stmt.bindString(9, customer.get(i).getLastDiscount() + "");
            stmt.bindString(10, customer.get(i).getModifyTime() + "");
            stmt.execute();
            stmt.clearBindings();
        }
        db.setTransactionSuccessful();
        db.endTransaction();
        Long b = System.currentTimeMillis();
        Log.i(TAG, String.valueOf(b - a));
        return 0;
    }

    public int updateAllPrice(List<FirstPrice> customer) {
        SQLiteDatabase db = DBHelper.open();
        db.beginTransaction();
        Long a = System.currentTimeMillis();
        Log.d(TAG, "updateAllPrice:" + customer.size());
        for (int i = 0; i < customer.size(); i++) {
            FirstPrice firstWarehouse = customer.get(i);
            String[] infos = Utils.replaceStr(firstWarehouse.getProductInfoId() + "").split("_");
            int length = infos.length;
            ContentValues cv = new ContentValues();
            //cv.put("idx", firstWarehouse.getIdx() + "");
            cv.put("idx", infos[length -1] + "" + firstWarehouse.getPriceTypeId());
            cv.put("productInfoId", infos[length -1] );
            cv.put("productInfoName", firstWarehouse.getProductInfoName() + "");
            cv.put("dealerId", firstWarehouse.getDealerId() + "");
            cv.put("priceTypeId", firstWarehouse.getPriceTypeId() + "");
            cv.put("priceTypeName", firstWarehouse.getPriceTypeName() + "");
            cv.put("taxSalePrice", firstWarehouse.getTaxSalePrice() + "");
            cv.put("noTaxSalePrice",  firstWarehouse.getNotaxSalePrice()  + "");
            cv.put("taxSaleSinglePrice", firstWarehouse.getTaxSaleSinglePrice() + "");
            cv.put("last_discount", firstWarehouse.getLastDiscount() + "");
            cv.put("modifyTime", firstWarehouse.getTimestamp() + "");
            db.insertWithOnConflict("Price", null, cv, SQLiteDatabase.CONFLICT_REPLACE); //如果有记录，则更新，并返回1，否则返回0
        }
        db.setTransactionSuccessful();
        db.endTransaction();
        Long b = System.currentTimeMillis();
        Log.i(TAG, String.valueOf(b - a));
        return 0;
    }

    public long getMaxModifyTime() {
        long param = 0;
        SQLiteDatabase db = DBHelper.open();
        Cursor cursor = db.rawQuery("select max(modifyTime)from Price ", new String[]{});
        Log.d(TAG, "getMaxModifyTime:getCount" + cursor.getCount());
        if (cursor.moveToFirst()) {
            param = cursor.getLong(0);
        }
        cursor.close();
        Log.d(TAG, "getMaxModifyTime:param" + param);
        return param;
    }

    public void deleteAll() {
        SQLiteDatabase db = DBHelper.open();
        db.execSQL("DELETE FROM Price");
    }

    public List<FirstPrice> findPrice(String productId) {
        List<FirstPrice> list = new ArrayList<>();
        SQLiteDatabase db = DBHelper.open();
        Cursor cursor = db.rawQuery("select * from Price where productInfoId =?", new String[]{productId});
        Log.d(TAG, "cursor:" + cursor.getCount());
        for (int i = 0; i < cursor.getCount(); i++) {
            cursor.moveToNext();
            FirstPrice customer = new FirstPrice();
            customer.setProductInfoId(cursor.getString(1));
            customer.setProductInfoName(cursor.getString(2));
            customer.setDealerId(cursor.getString(3));
            customer.setPriceTypeId(cursor.getString(4));
            customer.setPriceTypeName(cursor.getString(5));
            customer.setTaxSalePrice(cursor.getString(6));
            customer.setNotaxSalePrice(cursor.getString(7));
            customer.setTaxSaleSinglePrice(cursor.getString(8));
            list.add(customer);
        }
        cursor.close();
        //db.close();
        Log.d(TAG, "findPrice:" + list.size());
        return list;
    }

    public String findLastDiscount(String productId,String customerId) {
        String discount = "";
        String priceType = "";
        String priceType1 = new ClientPriceDB().getPriceType(SharedPreference.getPreferString("dealer"), SharedPreference.getPreferString("org"),SharedPreference.getPreferString("id"),customerId);//获取商店的关联价格套
        String defaultType1 = new PriceTypeDB().getDefault();//默认价格套
        if(!StringUtil.isEmpty(priceType1)){
            priceType = priceType1;
        } else if (!StringUtil.isEmpty(defaultType1)){
            priceType = defaultType1;
        } else {
            return "";
        }
        Log.d(TAG, "findLastDiscount:" + discount);
        SQLiteDatabase db = DBHelper.open();
        Cursor cursor = db.rawQuery("select * from Price where productInfoId=? and priceTypeId= ?", new String[]{productId, priceType});
        for (int i = 0; i < cursor.getCount(); i++) {
            cursor.moveToNext();
            discount = cursor.getString(9);
            Log.d(TAG, "findLastDiscount:" + discount + " productId:" +productId);
            return discount;
        }
        cursor.close();
        return discount;
    }

    public String getPrice( String productId,String customerId) {
        String mPrice = "";
        String priceType = new ClientPriceDB().getPriceType(SharedPreference.getPreferString("dealer"), SharedPreference.getPreferString("org"),SharedPreference.getPreferString("id"),customerId);//获取商店的关联价格套
        String defaultType = new PriceTypeDB().getDefault();//默认价格套

        List<FirstPrice> list = findPrice(productId);//获取商品所有价格信息，首先取关联价格套数据，再取默认，再取商品本身价格
        Log.d(TAG, "getPrice:priceType-" + priceType+"  defaultType："+defaultType + "  findPrice：" +list.size() + ",productId:"+productId);
        if(list.size() > 0){
            for(FirstPrice price: list){
                if(!StringUtil.isEmpty(priceType)){
                    if(price.getPriceTypeId().equals(priceType)){
                        Log.d(TAG, "getPrice:getPriceTypeId-" + price.getTaxSalePrice());
                        mPrice=  String.valueOf(Double.valueOf(price.getTaxSalePrice())) + "_1";
                    }
                } else {
                    if(!StringUtil.isEmpty(defaultType)){
                        Log.d(TAG, "getPrice:defaultType-" + price.getTaxSalePrice());
                        if(price.getPriceTypeId().equals(defaultType)){
                            mPrice=  String.valueOf(Double.valueOf(price.getTaxSalePrice()))+ "_1";
                        }
                    }
                }
            }
            if(mPrice.equals("")){
                mPrice = new ShopsDB().getDefaultPrice(productId)+ "_2";
                Log.d(TAG, "getPrice:getDefaultPrice-" + mPrice);
            }
        } else{
            mPrice = new ShopsDB().getDefaultPrice(productId)+ "_2";
            Log.d(TAG, "getPrice:getDefaultPrice-" + mPrice);
        }
        Log.d(TAG, "getPrice:" + mPrice);
        return mPrice;
    }

    public String getNotexSalePrice(String productId,String customerId) {
        String mPrice = "";
        String priceType = new ClientPriceDB().getPriceType(SharedPreference.getPreferString("dealer"), SharedPreference.getPreferString("org"),SharedPreference.getPreferString("id"),customerId);//获取商店的关联价格套
        List<FirstPrice> list = findPrice(productId);//获取商品所有价格信息，首先取关联价格套数据，再取默认，再取商品本身价格
        if(list.size() > 0){
            for(FirstPrice price: list){
                if(!StringUtil.isEmpty(priceType)){
                    if(price.getPriceTypeId().equals(priceType)){
                        mPrice=  price.getNotaxSalePrice();
                    }
                }
            }
        }
        Log.d(TAG, "getNotexSalePrice:" + mPrice);
        return mPrice;
    }

    public boolean hasData() {
        SQLiteDatabase db = DBHelper.open();
        Cursor cursor = db.rawQuery("select count(*)from Price", null);
        cursor.moveToFirst();
        Long count = cursor.getLong(0);
        if (count > 0) {
            cursor.close();
            Log.d(TAG, "hasPrice true");
            return true;
        } else {
            Log.d(TAG, "hasPrice false");
            cursor.close();
            return false;
        }
    }

    public long dataNum() {
        SQLiteDatabase db = DBHelper.open();
        Cursor cursor = db.rawQuery("select count(*)from Price", null);
        cursor.moveToFirst();
        Long count = cursor.getLong(0);
        if (count > 0) {
            cursor.close();
            Log.d(TAG, "hasShops true");
            return count;
        } else {
            Log.d(TAG, "hasShops false");
            cursor.close();
            return count;
        }
    }

}
